package com.jwell.panprovider.ui.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.view.WindowManager
import com.jwell.cargoapp.ui.base.MVPBaseActivity
import com.jwell.panprovider.R
import com.jwell.panprovider.contract.LoginContract
import com.jwell.panprovider.presenter.LoginPresenter
import kotlinx.android.synthetic.main.activity_login.*
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import com.jwell.driverapp.retrofit.RetrofitFactory
import com.jwell.panprovider.entity.Account
import com.jwell.panprovider.tools.DataModel
import com.squareup.picasso.Picasso
import java.util.*

/**
 * 登录界面
 */
class LoginActivity : MVPBaseActivity<LoginPresenter>(), LoginContract.View, View.OnClickListener {
    private var mRandomCount:Int=0;

    override fun sendMsgSuccess() {
        hideProgress()
        toast("短信验证码发送成功")
        mVerificationTimer.start()
    }

    override fun loginByPhoneSuccess() {
        hideProgress()
        skipToMain(null)
    }

    private var isCanSeePassWord = false
    private val RESET_PASSWORD = 1
    override fun createPresenter(): LoginPresenter? {
        return LoginPresenter()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(R.layout.activity_login)
        setTransportStatusBar()
        setListener()
        when (DataModel.getInstance().loginCheckBox) {
            true -> {
                val account: Account? = DataModel.getInstance().account
                setUserName(account?.userName, account?.passWord)
            }
            false -> {
                val account = DataModel.getInstance().account
                setUserName(account?.userName, "")
            }
        }
    }

    private fun setListener() {
        text_forgetPassword.setOnClickListener(this)
        btn_login.setOnClickListener(this)
        image_switch.setOnClickListener(this)

        tv_pass_btn.setOnClickListener(this)
        tv_code_btn.setOnClickListener(this)
        tv_get_code.setOnClickListener(this)
        iv_pic_code.setOnClickListener(this)
        btn_login_code.setOnClickListener(this)
    }
    fun showPicCode()
    {
        var random: Random = Random()
        mRandomCount=random.nextInt(10000);
        var url:String= RetrofitFactory.BASE_URL+"api/AdminAccount/GetVerifyCode?userSessionId="+mRandomCount
        Picasso.with(this).load(url).into(iv_pic_code)
    }
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.text_forgetPassword -> {
                var intent = Intent(this, ForgetPasswordActivity::class.java)
                startActivityForResult(intent, RESET_PASSWORD)
            }
            R.id.btn_login -> {
                if (edit_userName.text.isNullOrEmpty()) {
                    toast("请输入用户名")
                    return
                }
                if (edit_userPassword.text.isNullOrEmpty()) {
                    toast("请输入密码")
                    return
                }
                showProgress("", true)
                presenter?.login(edit_userName.text.toString(), edit_userPassword.text.toString(), checkbox_switch.isChecked)
            }
            R.id.image_switch -> {
                isCanSeePassWord = !isCanSeePassWord
                when (isCanSeePassWord) {
                    true -> {
                        image_switch.setImageResource(R.mipmap.icon_openyoureyes)
                        //如果是能看到密码的情况下，
                        edit_userPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
                    }
                    false -> {
                        image_switch.setImageResource(R.mipmap.icon_closeyoureyes)
                        //如果是不能看到密码的状态下
                        edit_userPassword.transformationMethod = PasswordTransformationMethod.getInstance()
                    }
                }
            }
            R.id.tv_code_btn -> {
                ll_code_login.visibility = View.VISIBLE
                ll_pass_login.visibility = View.GONE
                showPicCode()
            }

            R.id.tv_pass_btn -> {
                ll_code_login.visibility = View.GONE
                ll_pass_login.visibility = View.VISIBLE
            }
            R.id.tv_get_code -> {

                if(TextUtils.isEmpty(edit_phone_code.text.toString().trim()))
                {
                    toast("请填写手机号码")
                    return
                }
                if(TextUtils.isEmpty(et_pic_code.text.toString().trim()))
                {
                    toast("请填写图形验证码")
                    return
                }
                showProgress("", true)
                presenter?.sendMsgCode(edit_phone_code.text.toString().trim(),mRandomCount.toString(),et_pic_code.text.toString().trim())

            }
            R.id.iv_pic_code->{
                showPicCode()
            }
            R.id.btn_login_code->{
                if(TextUtils.isEmpty(edit_userName_code.text.toString().trim()))
                {
                    toast("请填写账号")
                    return
                }
                if(TextUtils.isEmpty(edit_phone_code.text.toString().trim()))
                {
                    toast("请填写手机号码")
                    return
                }
                if(TextUtils.isEmpty(et_pic_code.text.toString().trim()))
                {
                    toast("请填写图形验证码")
                    return
                }
                showProgress("", true)
                presenter?.loginByPhoneCode(edit_userName_code.text.toString().trim(),edit_phone_code.text.toString().trim(),et_msg_code.text.toString().trim())
            }
        }
    }

    override fun loginFaild(message: String) {
        toast(message)
    }

    override fun loginSuccessful() {
        skipToMain(null)
    }

    override fun setUserName(name: String?, passWorld: String?) {
        edit_userName.setText(name)
        edit_userPassword.setText(passWorld)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == RESET_PASSWORD) {
            if (resultCode == Activity.RESULT_OK) {
                data?.getStringExtra("pwd")?.let {
                    edit_userPassword.setText(it)
                }
            }
        }
    }

    private val mVerificationTimer = object : CountDownTimer((60 * 1000).toLong(), 1000) {
        override fun onTick(millisUntilFinished: Long) {
            tv_get_code.isEnabled = false
            tv_get_code.setTextColor(Color.parseColor("#999999"))
            tv_get_code.text = getString(R.string.account_get_verification_code_cd, millisUntilFinished / 1000)
        }

        override fun onFinish() {
            tv_get_code.isEnabled = true
            tv_get_code.setTextColor(Color.parseColor("#2ecc71"))
            tv_get_code.text = getString(R.string.tv_resend_code)
        }
    }
}
